﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using InnovTech.Persistence;
using NHibernate.Cfg;
using NHibernate.Connection;
using NHibernate.Dialect;
using NHibernate.Driver;

namespace NHibernate.MsSqlCe
{
    /// <summary>
    /// Represents the important infos to connect a MS-Sql-Ce database.
    /// </summary>
    public class NHMsSqlCeDatabaseInfo : INHDatabaseInfo, INHMsSqlCeDbInfo
    {

        static readonly Dictionary<string, string> Default_Configuration_Properties;

        static NHMsSqlCeDatabaseInfo()
        {
            Default_Configuration_Properties = new Dictionary<string, string>();
            Default_Configuration_Properties.Add(NHibernate.Cfg.Environment.Dialect, typeof(MsSqlCeDialect).AssemblyQualifiedName);
            Default_Configuration_Properties.Add(NHibernate.Cfg.Environment.ConnectionDriver, typeof(SqlServerCeDriver).AssemblyQualifiedName);
            Default_Configuration_Properties.Add(NHibernate.Cfg.Environment.ConnectionProvider, typeof(DriverConnectionProvider).AssemblyQualifiedName);
            //to avoid the Bug "null identity" using the following settings for ReleaseConnections
            //http://stackoverflow.com/questions/2361730/assertionfailure-null-identifier-fluentnh-sqlserverce
            Default_Configuration_Properties.Add(NHibernate.Cfg.Environment.ReleaseConnections, "on_close");

        }

        /// <summary>
        /// Gets or sets the path of a ms-sql-ce database.
        /// </summary>
        public string DatabasePath { get; set; }
        /// <summary>
        /// Gets or sets the value which indicates whether the content of the ms-sql-ce database should be encryted.
        /// </summary>
        public bool Encrypted { get; set; }
        /// <summary>
        /// Gets or sets the password to access the ms-sql-ce database.
        /// </summary>
        public string Password { get; set; }
        /// <summary>
        /// Gets or sets the properties for NHibernate.
        /// </summary>
        public Dictionary<string, string> Properties { get; set; }
        

        public Action<Configuration> MappingAction { get; set; }


        public string GetConnectionString()
        {
            return string.Format(@"Data Source={0}; File Mode=Exclusive; Encrypt={1}; Password={2};", DatabasePath, Encrypted, Password);
        }

        public Dictionary<string, string> GetConfigurationProperties()
        {
            return Properties ?? Default_Configuration_Properties;
        }

        public Action<TMappingTarget> GetMappingAction<TMappingTarget>()
        {
            return new Action<TMappingTarget>(target =>
            {
                Configuration config = target as Configuration;
                MappingAction(config);
            });
        }
    }
}
